(function(){
	$.fn.ConstructForm = function(){
		var calc = $(this);
		var question = calc.find('#question');
		var history = calc.find('#history');
		var construct = {
			
			updPop : function(obj){
				//console.log(obj);

				var cont = $("#question");
				cont.html("<h2>" + obj.name + "</h2>");
				$.each(obj.answers, function(index, item){
					//console.log(index);
					cont.append("<li class='answer' rel='" + obj.id + "' ><a rel='" + index + "' href='#'>" + item.name + "</a></li>");

				});

			},
			updHist : function(id_q, id_a){
				var cont = $("#history");
				var name = construct.struct[id_q].name;
				var answer = construct.struct[id_q].answers[id_a].name;
				//console.log(name);
				cont.append("<p>" + name + "&nbsp;:&nbsp;" + answer + "</p>");
			},
			init : function(){
				construct.updPop(construct.struct[0]);
			},
			showFinish : function(){
				var cont = $("#question");
				cont.append("<input type='submit' value='отправить'></input>");
			},

			struct : {
				0 : {
					id : 0,
					name : "первый",
					answers : {
						0 : {
							name : "a"
						},
						1 : {
							name : "b"
						},
						2 : {
							name : "c"
						}
					}
				},
				1 : {
					id : 1,
					name : "второй",
					answers : {
						0 : {
							name : "a"
						},
						1 : {
							name : "b"
						}
					}
				},
				2 : {
					id : 2,
					name : "третий",
					answers : {
						0 : {
							name : "a"
						}
					}
				}
			}
		};
		//binds
		$(document).on("click", "#calc #question li.answer", function(e){
			// console.log($(this).attr("rel"));
			var a = $(this).find("a");
			// console.log($(a).attr("rel"));
			construct.updHist($(this).attr("rel"), $(a).attr("rel"));
			if(construct.struct[parseInt($(this).attr("rel"), 10)+1] != undefined){
				construct.updPop(construct.struct[parseInt($(this).attr("rel"), 10)+1]);
				if (construct.struct[parseInt($(this).attr("rel"), 10)+2] == undefined){
					$(document).off("click", "#calc #question li.answer");
					construct.showFinish();
				}	
			}

			e.preventDefault();
		});

		construct.init();
		//console.log(construct);
	}

})();
